package org.turbobytes.unikey.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Number related utility methods
 *
 * @author Ganeshji Marwaha
 * @since Aug 6, 2010
 */
public class NumberUtil {
  private static final Log log = LogFactory.getLog(FileUtil.class);

  /**
   * Convert from a string value to long value. It is null safe. Also returns 0L if it the string
   * cannot be resolved to a long
   * @param stringValue - to convert to long
   * @return converted long value
   */
  public static Long stringToLong(String stringValue) {
    return stringToLong(stringValue, 0L);
  }

  /**
   * Convert from a string value to long value. It is null safe. Also returns {@param defaultValue }
   * if it the string cannot be resolved to a long
   * @param stringValue - to convert to long
   * @param defaultValue - to use in case of conversion failure
   * @return converted long value
   */  
  public static Long stringToLong(String stringValue, Long defaultValue) {
    if(stringValue == null) return defaultValue;
    
    Long longValue = defaultValue;
    try {
      longValue = Long.valueOf(stringValue);
    } catch(Exception e) {
      log.warn("Cannot convert from " + stringValue + " to Long Value. Reverting to default value", e);
    }
    return longValue;
  }

  /**
   * Checks whether the given string can represent a number
   * @param strNumber - to check
   * @return if the given string is a number or not
   */
  public static boolean isNumber(String strNumber) {
    try {
      Double.parseDouble(strNumber);
    } catch (Exception e) {
      return false;
    }
    return true;
  }

  /**
   * Checks whether the given string represents a whole number (without fractions)
   * @param strNumber - to check
   * @return if the given string is a whole number or not
   */
  public static boolean isWholeNumber(String strNumber) {
    try {
      Long.parseLong(strNumber);
    } catch (Exception e) {
      return false;
    }
    return true;
  }

  /**
   * Checks whether the given string represents a positive whole number (without fractions and negative values)
   * @param strNumber - to check
   * @return if the given string is a positive whole number or not
   */
  public static boolean isPositiveWholeNumber(String strNumber) {
    Long longValue;
    try {
      longValue = Long.parseLong(strNumber);
    } catch (Exception e) {
      return false;
    }

    return longValue >= 0;
  }

}
